package com.jstyle.devicenametest.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;


import androidx.core.content.FileProvider;

import com.jstyle.devicenametest.BuildConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtils {


    public static final long oneMinMillis = 60 * 1000l;
    static int durationDays = 60;

    public static String[] getFileInfo(File from) {
        String fileName = from.getName();
        int index = fileName.lastIndexOf(".");
        String toPrefix = "";
        String toSuffix = "";
        if (index == -1) {
            toPrefix = fileName;
        } else {
            toPrefix = fileName.substring(0, index);
            toSuffix = fileName.substring(index, fileName.length());
        }
        return new String[]{toPrefix, toSuffix};
    }

    public static File createOrRenameFile(File from) {
        String[] fileInfo = getFileInfo(from);
        String toPrefix = fileInfo[0];
        String toSuffix = fileInfo[1];
        File file;
        file = createOrRenameFile(from, toPrefix, toSuffix);
        return file;

    }

    public static File createOrRenameFile(File from, String toPrefix, String toSuffix) {
        File directory = from.getParentFile();
        if (!directory.exists()) {
            if (directory.mkdir()) {
                Log.v(TAG, "Created directory " + directory.getAbsolutePath());
            }
        }
        File newFile = new File(directory, toPrefix + toSuffix);
        for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
            newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix);
        }
        if (!from.renameTo(newFile)) {
            Log.w(TAG, "Couldn't rename file to " + newFile.getAbsolutePath());
            return from;
        }
        return newFile;
    }







    public static void shareByPhone(Context context, String path) {
        Uri imageUri = null;
        Intent shareIntent = new Intent();
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    BuildConfig.APPLICATION_ID+".fileprovider", new File(path));
            context.grantUriPermission(context.getPackageName(), imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        } else {
            imageUri = Uri.fromFile(new File(path));
        }

        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("*/*");
        context.startActivity(Intent.createChooser(shareIntent, "Share"));
        Log.i(TAG, "shareByPhone: ");
    }

    private static final String TAG = "CsvUtils";

    private static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }



    private static void writeRowContent(String[] values, BufferedWriter csvWriter) throws IOException {
        for (String data : values) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(TextUtils.isEmpty(data) ? "--" : data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();

    }


    private static void writeRowContent(BufferedWriter csvWriter, String value) throws IOException {
        StringBuffer sb = new StringBuffer();
        String content = sb.append("\"").append(value).append("\",").toString();
        csvWriter.write(content);
    }



    public static int get1MIndex(String time, String defaultTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        int count = 0;
        try {
            Date date = format.parse(time + " 00:00:00");
            Date dateBase = format.parse(defaultTime);
            long min = dateBase.getTime() - date.getTime();
            count = (int) (min / oneMinMillis);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return count;
    }

    static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    public static String getCountTime(int count, long defaultTime) {

        //   String base = "00:00:00";
        long time = defaultTime + count * oneMinMillis;

        return format.format(new Date(time));
    }


    public static String getRootPath(Context context) {
        return context.getExternalFilesDir("").getAbsolutePath();
    }

    public static void shareFile(Context context, List<String[]> content, String[] title, String path) {
        File csvFile = null;

        BufferedWriter csvWtriter = null;
        csvFile = new File(getRootPath(context), path);
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        if (csvFile.exists())
            csvFile.delete();
        try {
            csvFile.createNewFile();
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
            List<String> headList = Arrays.asList(title);
            writeRow(headList, csvWtriter);
            for (String[] data : content) {
                for (String c : data) {
                    writeRowContent(csvWtriter, c);
                }
                csvWtriter.newLine();
            }
            csvWtriter.flush();
            csvWtriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        shareByPhone(context, csvFile.getAbsolutePath());
    }


}
